package com.byteblogs.helloblog.config;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import com.byteblogs.helloblog.bean.SystemPropertyBean;
import com.byteblogs.helloblog.constants.Constant;
import com.byteblogs.helloblog.dto.AuthDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * Feign请求拦截器（设置请求头，传递token信息）
 *
 * @author byteblogs
 **/
@Component
public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {

    @Autowired
    private SystemPropertyBean systemPropertyBean;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        long milli = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        String encode = Base64.encode(systemPropertyBean.getAccessKey() + ":" + systemPropertyBean.getSecretKey());
        HMac mac = new HMac(HmacAlgorithm.HmacMD5, encode.getBytes());
        AuthDTO authDTO = new AuthDTO();
        authDTO.setSign(mac.digestHex(encode));
        authDTO.setAk(Base64.encode(systemPropertyBean.getAccessKey()));
        authDTO.setMilli(milli);

        ObjectMapper mapper = new ObjectMapper();
        try {
            requestTemplate.header(Constant.HELLOBLOG_AUTHENTICATION, mapper.writeValueAsString(authDTO));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}